/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cn.yunyichina.provider.framework.annotation.validate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.regex.Pattern;

/**
 * Validate the @ValidatePattern annotation
 *
 * @author jiangtch
 */
public class ValidatePatternHandler implements Handler {

    private static final Logger logger = LoggerFactory.getLogger(ValidatePatternHandler.class);

    public void validate(AnnotationValidable validatedObj, Field field)
            throws ValidateException {
        if (logger.isTraceEnabled()) {
            logger.trace(this.getClass().getName(), "validate()");
        }
        if (field.isAnnotationPresent(ValidatePattern.class)) {
            checkString(validatedObj, field);
        }
    }

    /**
     * validate the String format
     *
     * @param filter validated object
     * @param field  validated field or property
     * @throws ValidateException validated exception
     */
    private void checkString(AnnotationValidable filter, Field field)
            throws ValidateException {
        if (logger.isTraceEnabled()) {
            logger.trace(this.getClass().getName(), "checkString()");
        }
        ValidatePattern annotation = field.getAnnotation(ValidatePattern.class);
        String patternStr = annotation.pattern();
        Object value;
        try {
            value = GetFiledValue.getField(filter, field.getName());
        } catch (Exception ex) {
            logger.error("字段：" + field.getName() + " 获取值发生异常->" + ex.getMessage(), ex);
            throw new ValidateException("字段：" + field.getName() + " 获取值发生异常->" + ex.getMessage(), ex);
        }
        checkStringFormat(field.getName(), patternStr, value);
    }

    /**
     * validate the String format
     *
     * @param patternStr validate regex pattern
     * @param value      validated value
     * @throws ValidateException validated exception
     */
    private void checkStringFormat(String fieldName, String patternStr, Object value) throws ValidateException {
        if (logger.isTraceEnabled()) {
            logger.trace(this.getClass().getName(), "checkStringFormat()");
        }
        String checkStr = (String) value;
        Pattern pattern = Pattern.compile(patternStr);
        if (checkStr != null) {
            String[] str = checkStr.split(",");
            for (String aStr : str) {
                if (!pattern.matcher(aStr).matches()) {
                    logger.warn("字段：" + fieldName + "校验失败,校验的值为:" + checkStr + ",当前值:" + aStr + "!");
                    throw new ValidateException("字段：" + fieldName + "校验失败,校验的值为:" + checkStr + ",当前值:" + aStr + "!");
                }
            }
        }
    }

}
